layui.use(['laydate', 'layer', 'form', 'table', 'configs', 'laytpl','util', 'echarts', 'formSelects'], function () {
    var $ = layui.jquery,
        laydate = layui.laydate,
        layer = layui.layer,
        form = layui.form,
        config = layui.configs,
        laytpl = layui.laytpl,
        util = layui.util,
        echarts = layui.echarts,
        formSelects = layui.formSelects;
    let areaId = null, flag = 0, laydateObj = {};
    // let myChart = echarts.init(document.getElementById("pie-chart"));
    var  myChart = null, chartArr = [], option = {};
    var initType = $('[name="trendType"]:checked').val();
    initAll();

    function initAll() {
        getArea();
        initLayDate(initType);
    }

    function initLayDate(charttype) {
        var sv = null;
        if (charttype === '1') { // 1-时 'yyyy-MM-dd HH:mm'
            //提前24小时
            sv = new Date(new Date().getTime() - 3600 * 1000 * 24);
            laydateObj = {
                startValue: formatDateStr(charttype, sv),
                endValue: formatDateStr(charttype),
                format: 'yyyy-MM-dd HH:mm',
                type: 'datetime',
                ready: function () { //删除分秒选择框，时选择居中
                    $(".layui-laydate .layui-laydate-footer").on("click", "span.laydate-btns-time", function () {
                        var hourLi = $(this).parents(".layui-laydate").find('.laydate-time-show .laydate-time-list > li:first-child');
                        hourLi.nextAll().remove();
                        hourLi.css("width", "100%");
                        hourLi.find("ol li").css({"padding-left": 115})
                    });
                }
            };
        } else if (charttype === '2') { // 2-日 'yyyy-MM-dd'
            //提前30天
            sv = new Date(new Date().getTime() - 3600 * 1000 * 24 * 30);
            laydateObj = {
                startValue: formatDateStr(charttype, sv),
                endValue: formatDateStr(charttype),
                format: 'yyyy-MM-dd',
                type: 'date',
                ready: function () {
                }
            };
        } else { // 3-月 'yyyy-MM'
            //提前一个月
            sv = new Date(new Date().getTime() - 3600 * 1000 * 24 * 30);
            laydateObj = {
                startValue: formatDateStr(charttype, sv),
                endValue: formatDateStr(charttype),
                format: 'yyyy-MM',
                type: 'month',
                ready: function () {
                }
            };
        }
        initDate(laydateObj);
    }

    function initDate(laydateObj) {
        laydate.render({
            elem: "#startTime",
            value: laydateObj.startValue,
            format: laydateObj.format,
            type: laydateObj.type,
            trigger: 'click',
            btns: ['clear', 'confirm'],
            ready: laydateObj.ready
        });
        laydate.render({
            elem: "#endTime",
            value: laydateObj.endValue,
            format: laydateObj.format,
            type: laydateObj.type,
            trigger: 'click',
            btns: ['clear', 'confirm'],
            ready: laydateObj.ready
        });
    }

    // 监听类型选择
    form.on('radio(trendType)', function (data) {
        var startIpt = '<input type="text" class="layui-input" id="startTime" name="startTime"  autocomplete="off">';
        var endIpt = '<input type="text" class="layui-input" id="endTime" name="endTime"  autocomplete="off">';
        $(".startTime").empty().html(startIpt);
        $(".endTime").empty().html(endIpt);
        initLayDate(data.value)
    });

    //获取区域
    function getArea() {
        $.ajax({
            url: config.motorBaseUrl + "/area_info/select/v1.0",
            type: "post",
            datatype: "json",
            data: {},
            success: function (result) {
                if (result.stateCode == 0) {
                    laytpl($('#area-tpl').html()).render(result, function (html) {
                        $('select.areaMenu').html(html)
                    });
                    form.render('select');
                    areaId = $("select.areaMenu option:checked").val();
                    getMotors(areaId);
                } else {
                    layer.alert(result.stateMsg);
                }
            }
        })
    }

    //监听区域选择
    form.on('select(areaMenu)', function (data) {
        flag = 1;
        $(".motorMenu").html('');
        areaId = data.value;
        getMotors(areaId);
    });

    // 按区域查马达
    function getMotors(areaId) {
        $.ajax({
            url: config.motorBaseUrl + "/mo_motors/selectMortor/v1.0",
            type: "post",
            datatype: "json",
            data: {
                areaId: areaId
            },
            success: function (result) {
                if (result.stateCode == 0) {
                    if (result.data != null && result.data.length > 0) {
                        laytpl($('#motor-tpl').html()).render(result, function (html) {
                            $('select.motorMenu').html(html)
                        });
                        form.render('select');
                        if (flag === 0) {
                            $(".searchBtn").click()
                        }
                    }
                } else {
                    layer.msg(result.stateMsg);
                }
            }
        })
    }

    //查询
    $(".searchBtn").click(function () {
        $('#pie-chart').empty();
        form.on('submit(search)', function (data) {
            getPie(data.field);
            return false;
        });
    });

    //饼图
    function getPie(dataobj) {
        $.ajax({
            url: config.motorBaseUrl + "/chart/get/trend/v1.0",
            type: "post",
            datatype: "json",
            data: dataobj,
            success: function (result) {
                if (result.stateCode == 0) {
                    var title = '【' + $('.areaMenu option:selected').text() +  $('.motorMenu option:selected').text() + '】'+ $("[name=trendType]:checked").attr("title");
                    var datas = result.data; // obj
                    var count = Object.keys(datas);
                    var list = Object.values(datas);
                    $('.chart-title h3').text(title);
                    if(list.length == 0){
                        $('#pie-chart').html('<h3>无数据</h3>')
                    }else{
                        var divs = '';
                        count.forEach(function(item, index){
                            divs += '<div id="pie-' + index + '"></div>'
                        });
                        $('#pie-chart').append(divs);
                        for(var i=0;i<list.length;i++){
                            var item = list[i][0];
                            myChart = echarts.init(document.getElementById('pie-' + i));
                            option = {
                                backgroundColor: 'transparent',
                                grid: {
                                    containLabel: true
                                },
                                title: {
                                    left: 'center',
                                    text: item.recTime,
                                    textStyle: {
                                        color: '#eee'
                                    }
                                },
                                series: [
                                    {
                                        name: '数据占比',
                                        type: 'pie',
                                        radius: '50%',
                                        center: ['50%', '60%'],
                                        label: {
                                            show: true,
                                            fontSize: 14,
                                            formatter: '{d}%'
                                        },
                                        data: [
                                            {
                                                name: '稼动率',
                                                value: isZero(item.dynamicRate),
                                                itemStyle: {
                                                    normal: {
                                                        color: '#28d428'
                                                    }
                                                }
                                            },
                                            {
                                                name: '保养率',
                                                value: isZero(item.maintainRate),
                                                itemStyle: {
                                                    normal: {
                                                        color: '#00BCD4'
                                                    }
                                                }
                                            },
                                            {
                                                name: '故障率',
                                                value: isZero(item.failureRate),
                                                itemStyle: {
                                                    normal: {
                                                        color: '#fe2216'
                                                    }
                                                }
                                            }
                                        ]
                                    }
                                ]
                            };
                            myChart.setOption(option);
                        }
                    }
                } else {
                    layer.msg(result.stateMsg);
                }
            }
        });
    }

    window.onresize = function () {
        myChart.resize();
    };

    function isZero(data){
       return data == 0 ? null : data
    }
    function substrLast(str){
        return str.substr(0, str.length - 1)
    }

    function formatDateStr(types, date) {
        var date = date || new Date();
        var Y = date.getFullYear();
        var M = date.getMonth() + 1;
        M = M < 10 ? '0' + M : M;
        var D = date.getDate();
        D = D < 10 ? '0' + D : D;
        var h = date.getHours();
        h = h < 10 ? '0' + h : h;
        var m = date.getMinutes();
        m = m < 10 ? '0' + m : m;
        if (types === '1') {
            return Y + '-' + M + '-' + D + ' ' + h + ':00';
        } else if (types === '2') {
            return Y + '-' + M + '-' + D;
        } else {
            return Y + '-' + M;
        }
    }
});